package com.ydlclass.loadbnlancer.impl;

import com.ydlclass.YrpcBootstrap;
import com.ydlclass.exceptions.LoadBalancerException;
import com.ydlclass.loadbnlancer.AbstractLoadBalance;
import com.ydlclass.loadbnlancer.Selector;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author duWenJian
 * @Date 2023/11/7 11:02
 * @Version 1.0
 */
@Slf4j
public class MinimumResponseTimeLoadBalancer extends AbstractLoadBalance {
    @Override
    protected Selector getSelector(List<InetSocketAddress> addressesList) {
        return new MinimumResponseTimeSelector(addressesList);
    }

    private static class MinimumResponseTimeSelector implements Selector{

        public MinimumResponseTimeSelector(List<InetSocketAddress> addressesList) {

        }

        @Override
        public InetSocketAddress getNext() {
            Map.Entry<Long, Channel> entry = YrpcBootstrap.ANSWER_TIME_CHANNEL_CACHE.firstEntry();
            if (entry!=null){
                if (log.isDebugEnabled()){
                    log.debug("最小响应时间负载均衡器获取到响应时间最小的节点：{},响应时间为{}",entry.getValue().remoteAddress(),entry.getKey());
                }
                return (InetSocketAddress)entry.getValue().remoteAddress();
            }
            Channel channel = (Channel)YrpcBootstrap.CHANNEL_CACHE.values().toArray()[0];
            return  (InetSocketAddress)channel.remoteAddress();
        }
    }
}
